//
//  SNStravaVc.swift
//  project
//
//  Created by 黄建华 on 2018/7/25.
//  Copyright © 2018年 黄建华. All rights reserved.
//

import UIKit

class SNStravaVc: SNBaseSubViewController,UIWebViewDelegate {
    public var url : URL!
    public var code: String!
    public var token: String!
    public var redirectURL : String!
    private var webView : UIWebView!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.code = SN_PublicClassSwift?.showStravaCode
        self.token = SN_PublicClassSwift?.showStravaToken
        
        let backButton = CreatUIButton(frame: SMakeRect(x1: 5, y1: ValueIXOrOther(ip: 20, ix: 40), width1: 44, height1: 44), text: "")
        backButton.setImage(UIImage(named:"进入"), for:.normal)
        backButton.addTarget(self, action: #selector(backView), for: .touchUpInside)
        self.view.addSubview(backButton)
        
        let titleLable = CreatUIlabel(frame: SMakeRect(x1: 0, y1: ValueIXOrOther(ip: 20, ix: 40), width1: ScreenWitdh, height1: 44), text:SMakeText(key: "Strava"))
        titleLable.font = UIFont.boldSystemFont(ofSize: 17)
        self.view.addSubview(titleLable)
        
        let line = SNShadowView(frame:SMakeRect(x1: 0, y1: ValueIXOrOther(ip: 64, ix: 84), width1: ScreenWitdh, height1: 2))
        line.show(withType: 1)
        self.view.addSubview(line)
        
        ShowMBProgressHUD(title:SMakeText(key: "请等待..."), time: 5.0)
        self.perform(#selector(gotoStrava), with: nil, afterDelay: 2.0);
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @objc func gotoStrava() {
        self.url = StravaLogin(clientID: Int(StravaClientID), redirectURI: StravaRedirectURI, approvalPrompt: ApprovalPrompt.force, accessScope: AccessScope.Write).makeURL()
        self.redirectURL = StravaRedirectURI
        UserDefaults.standard.register(defaults: ["UserAgent": "StravaZpot"])
        
        self.webView = UIWebView(frame: CGRect(x: 0, y:ValueIXOrOther(ip: 64, ix: 84), width: self.view.frame.size.width, height: self.view.frame.size.height-ValueIXOrOther(ip: 64, ix: 84)))
        self.view.addSubview(webView)
        print("url>>>>>>\(self.url)")
        self.webView.loadRequest(URLRequest(url: self.url))
        self.webView.delegate = self
    }
    
    public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if let loadingURL = request.mainDocumentURL,
            let code = loadingURL.valueOf(queryParameterName: "code"){
            if loadingURL.absoluteString.hasPrefix(redirectURL) {
                print("code >>>>>>>>>>\(code)")
                SN_PublicClassSwift?.stravaCode = code;
                self.code = code;
                getToken()
                return false
            }
        }
        return true
    }
    
    func getToken(){
        print("code>>>>>>>>>>>\(self.code)")
    let client = HTTPClientBuilder.authenticationClient(debug: true)
     AuthenticationAPI(client: client).getToken(forApp: AppCredentials(clientID: 26929,
                                             clientSecret: "a432aee41582f96dd45ba7d3de2069b05833f7d0"),
                                                withCode: self.code).execute { (refult) in
            print("get token result >>>>\(refult)")
            ShowMBProgressHUD(title:SMakeText(key: "授权成功"), time: 1.0)
             self.perform(#selector(self.backView), with: nil, afterDelay: 1.0);
        }
    }
    
    @objc func backView ()
    {
        self.navigationController?.popViewController(animated: true)
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
